package com.school.admin.common.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.school.admin.common.config.SystemConfig;
import com.school.admin.common.handler.GlobalException;
import com.school.admin.common.result.BaseResult;
import com.school.admin.common.result.RedisKeyResult;
import com.school.admin.common.result.ResultCode;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: houses-java-api
 * @description: 参数转换工具类
 * @author: sunpx
 * @create: 2021-07-07 14:10
 **/
public class ConversionParametersUtils {

    public static AES aes = SecureUtil.aes("dmpRz4zcToKthoj@".getBytes(StandardCharsets.UTF_8));


    /**
     * 生成Sing
     *
     * @param expireDate 过期时间
     * @param data       少量数据
     * @param belonging  签名所有者
     * @return java.lang.String
     * @author : sunpx
     * @date : 2021-07-08 11:16:01
     */
    public static String generateSign(Long expireDate, String data, String belonging) {
        long time = System.currentTimeMillis();
        HashMap<String, Object> returnHashMap = new HashMap<>();
        returnHashMap.put("expireDate", expireDate + time);
        returnHashMap.put("data", data);
        returnHashMap.put("issuanceTime", time);
        returnHashMap.put("belonging", belonging);
        String s = JSONUtil.parse(returnHashMap).toJSONString(0);

        return aes.encryptBase64(s);
    }


    public static boolean parsingSign(Object handler,String ciphertext){
        String s;

        try {
            s = aes.decryptStr(ciphertext);
        } catch (Exception e) {
            throw new GlobalException(ResultCode.SIGN_AUTHOR_ERROR, "sing解析失败");
        }

        JSONObject jsonObject = JSONUtil.parseObj(s);

        // 验证sign是否过期
        String belonging = (String) jsonObject.get("belonging");
        Object hget = RedisKeyResult.redisUtil.hget(BaseResult.RedisKeyResult.USER_LOGIN, BaseResult.RedisKeyResult.USER_LOGIN_KEY + belonging);
        if (hget == null) {
            throw new GlobalException(ResultCode.SIGN_EXPIRED, "sign过期");
        }
        String data = jsonObject.get("data").toString();
        UserLogInfoDto userLogInfoDto = JSONUtil.toBean(hget.toString(), UserLogInfoDto.class);
        if (SystemConfig.uniqueLogin){
            Object loginKey = RedisKeyResult.redisUtil.get(BaseResult.RedisKeyResult.LOGIN_AUTHENTICATION + userLogInfoDto.getUserId());
            if (loginKey == null){
                throw new GlobalException(ResultCode.SIGN_EXPIRED, "登录过期");
            }
            String loginThisKey = userLogInfoDto.getLoginKey();
            if (!loginKey.equals(loginThisKey)) {
                throw new GlobalException(ResultCode.SIGN_AUTHOR_ERROR, "您已在其他地方登录,请重新登录");
            }else{
                RedisKeyResult.redisUtil.set(BaseResult.RedisKeyResult.LOGIN_AUTHENTICATION+userLogInfoDto.getUserId(),loginKey, SystemConfig.loginExpirationTime * 1000);
            }
        }




        String s1 = String.valueOf(RedisKeyResult.redisUtil.hmget(BaseResult.SysTypeMapping.SYS_PARAMETER.getType()).get(BaseResult.DicTypeResult.SYS_PARAMETER_SING_FAIL_TIME));
        s1= "null".equals(s1)?"1800000":s1;
        //更新时间
        RedisKeyResult.redisUtil.hset(BaseResult.RedisKeyResult.USER_LOGIN, BaseResult.RedisKeyResult.USER_LOGIN_KEY + belonging, data, Long.valueOf(s1));


        // 用户是否用拥有接口权限
        Map<Object, Object> hmget = RedisKeyResult.redisUtil.hmget(BaseResult.SysTypeMapping.INTERFACE_REQUIRED_ROLE.getType());
        Object address = hmget.get(handler.toString());

        //如果为null说明没有控制
        if (address!=null){

            if (StringUtils.isEmpty(UserInfoUtil.getRoleId())) {
                throw new GlobalException(5001, "登录过期");
            }
            boolean contains=false;
            // 判断是否包含权限
            for (String qx : UserInfoUtil.getRoleId().split(",")) {
                contains = address.toString().contains(qx);
            }
            if (!contains){
                throw new GlobalException(ResultCode.AUTH, "权限不足");
            }
        }



        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userLogInfoDto);
        stringObjectMap.put("sign", ciphertext);


        UserInfoUtil.setUserInfoPutAll(stringObjectMap);

        return true;
    }

    /**
     * 验证权限
     * @author : sunpx
     * @param
     * @return void
     * @date : 2022-03-24 17:13:44
     */
    private static void verifyPermission(){



    }

}
